﻿using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

using EmbeddedSensorCloud.HTTP;
using SWE4.Data.EmbeddedSensorCloud.DTO.Response;
using Newtonsoft.Json;

namespace EmbeddedSensorCloud.Plugin.MicroERP
{
    public class FindCustomersCommand : ICommand
    {
        #region Fields

        private ICustomerDAO _CustomerDao;
        private JsonSerializerSettings _JsonSettings;

        #endregion

        #region Constructor

        public FindCustomersCommand(ICustomerDAO customerDao, JsonSerializerSettings jsonSettings)
        {
            this._CustomerDao = customerDao;
            this._JsonSettings = jsonSettings;
        }

        #endregion

        #region ICommand

        public bool CanExecute(Request param)
        {
            return (param.Method.ToUpperInvariant() == "GET" &&
                    param.Args.ContainsKey("q") &&
                    Regex.IsMatch(param.Url, @"^/api/customer[/]?$", RegexOptions.IgnoreCase));
        }

        public ResponseEntity Execute(Request param)
        {
            string searchText = param.Args.GetValueIfKey("q");
            string customerType = param.Args.GetValueIfKey("type");

            if (string.IsNullOrWhiteSpace(searchText) || (customerType != "" && customerType.ToLowerInvariant() != "company"))
            { throw new BadRequestException(); }

            IEnumerable<CustomerResponseModel> models = this._CustomerDao.Read(searchText, (customerType != ""));
            string returnString = JsonConvert.SerializeObject(models, this._JsonSettings);

            return new ResponseEntity(Encoding.UTF8.GetBytes(returnString), HttpStatusCode.OK);
        }

        #endregion
    }
}
